package com.zxy.h2demo;

import java.sql.*;

import org.h2.tools.Server;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * TCPServer.
 * 
 * Created by zxybird on 17/2/3.
 */
public class TCPServer {


  public static void main(String[] args) throws Exception {
    Server server;
    try {
      System.out.println("正在启动h2...");
      server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", String.valueOf("8802"));
      server.start();
    } catch (SQLException e) {
      System.out.println("启动h2出错：" + e.toString());
      // TODO Auto-generated catch block
      e.printStackTrace();
      throw new RuntimeException(e);
    }

    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:mem:db;MODE=MySQL;DB_CLOSE_DELAY=-1;","sa","sa");
    Statement stmt = conn.createStatement();
    stmt.execute("CREATE SCHEMA IF NOT EXISTS TRUMP;");
    stmt.execute("SET SCHEMA TRUMP;");
    stmt.executeUpdate("CREATE TABLE `trump`.`TEST_MEM`(ID INT PRIMARY KEY,NAME VARCHAR(255));");
    stmt.executeUpdate("INSERT INTO `trump`.`TEST_MEM` VALUES(1, 'Hello_Mem');");

    stmt.close();
    conn.close();

    ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:application-context.xml");
    ComboPooledDataSource dbSource = (ComboPooledDataSource) ctx.getBean("dbDataSource");
    Connection conn1 = dbSource.getConnection();
    Statement stmt1 = conn1.createStatement();

    ResultSet rs = stmt1.executeQuery("SELECT * FROM `trump`.`TEST_MEM`");

    while (rs.next()) {
      System.out.println(rs.getInt("ID") + "," + rs.getString("NAME"));
    }
    conn1.close();

    server.stop();
  }
}
